package com.lottemall.gateway.filters;

import com.lottemall.auth.entity.UserInfo;
import com.lottemall.auth.utils.JwtUtils;
import com.lottemall.common.utils.CookieUtils;
import com.lottemall.gateway.config.FilterProperties;
import com.lottemall.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 网关处理授权的过滤器
 */
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class AuthFilter extends ZuulFilter {


    @Autowired
    private JwtProperties jwtProperties;

    //注入白名单
    @Autowired
    private FilterProperties filterProperties;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE; //过滤器类型4个，这个是前置，我们看到是请求来了之前处理用户是否授权，不用等请求处理完了这里再来过滤就没用了。
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1; //过滤器顺序，一般在官方写的过滤器前面，这里就减一
    }

    /**
     * 是否过滤
     * @return 返回true是进行过滤
     */
    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = ctx.getRequest();
        //获取请求的url路径(得到的路径是浏览器地址栏域名后第一个斜杠开始，包括斜杠)
        String path = request.getRequestURI();
        //判断是否过滤
        return !isAllowPath(path);
    }

    /**
     * 判断当前用户请求的路径是否需要过滤   是否在白名单集合中有
     * @param path
     * @return
     */
    private boolean isAllowPath(String path) {
        //遍历白名单
        for (String allowPath : filterProperties.getAllowPaths()) {
            //判断是否允许
            if (path.startsWith(allowPath)){ //判断是否是以这个allowPath开始的
                return true;
            }
        }
        return false;
    }

    /**
     * 这里面主要写过滤的真正逻辑
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = ctx.getRequest();
        //获取cookie中的token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        try {
            //解析token
            UserInfo userInfo = JwtUtils.getUserInfo(jwtProperties.getPublicKey(), token);
            // TODO 校验权限
        } catch (Exception e) {
            //解析token失败，未登录，拦截
            ctx.setSendZuulResponse(false);  //默认是放行的，写了false就是拦截
            //返回状态码
            ctx.setResponseStatusCode(403);
        }
        return null;
    }
}
